package biometria.server;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.mindrot.jbcrypt.BCrypt;

import biometria.client.service.LoginService;
import biometria.server.dao.impl.BaseDAOImpl;
import biometria.shared.User;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
public class LoginServiceImpl extends RemoteServiceServlet implements LoginService {

	private static final long serialVersionUID = 4456105400553118785L;
	private Logger logger = Logger.getLogger(BaseDAOImpl.class);
	
	@Override
	public User loginServer(String name, String password) {
		logger.info("TEST");
		name = escapeHtml(name);
		password = escapeHtml(password);
		password = BCrypt.hashpw(password, BCrypt.gensalt());
		User user = new User(name, password);
		// validate username and password
		if (true) {
			user.setSessionID(String.valueOf(System.currentTimeMillis()));
			user.setLogged(true);
			// store the user/session id
			storeUserInSession(user);
		}

		return user;
	}


	@Override
	public User loginFromSessionServer() {
		return getUserAlreadyFromSession();
	}

	@Override
	public void logout() {
		deleteUserFromSession();
	}

	@Override
	public Boolean changePassword(String name, String newPassword) {
		return false;
		// change password logic
	}

	private User getUserAlreadyFromSession() {
		User user = null;
		HttpServletRequest httpServletRequest = this.getThreadLocalRequest();
		HttpSession session = httpServletRequest.getSession();
		Object userObj = session.getAttribute("user");
		if (userObj != null && userObj instanceof User) {
			user = (User) userObj;
		}
		return user;
	}

	private void storeUserInSession(User user) {
		HttpServletRequest httpServletRequest = this.getThreadLocalRequest();
		HttpSession session = httpServletRequest.getSession(true);
		session.setAttribute("user", user);
	}

	private void deleteUserFromSession() {
		HttpServletRequest httpServletRequest = this.getThreadLocalRequest();
		HttpSession session = httpServletRequest.getSession();
		session.removeAttribute("user");
	}

	/**
	 * Escape an html string. Escaping data received from the client helps to
	 * prevent cross-site script vulnerabilities.
	 * 
	 * @param html
	 *            the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}
}
